package com.lanhao.aot;

import java.util.*;
import java.util.regex.*;

public class AddressSplitter {

    private static final String[] LEVELS = {
        "省", "市", "区县", "乡镇街道", "路/巷/街", "门牌号码",
        "小区/行政村/单位/楼宇", "楼栋", "单元", "层", "房号"
    };

    private static final List<Pattern> PATTERNS = Arrays.asList(
        Pattern.compile("^(.*?省)"),
        Pattern.compile("^(.*?市)"),
        Pattern.compile("^(.*?[区县])"),
        Pattern.compile("^(.*?(?:街道|镇|乡))"),
        Pattern.compile("^(.*?(?:路|街|巷))"),
        Pattern.compile("^(.*?\\d+号)"),
        Pattern.compile("^(.*?(?:小区|村|大厦|花园|工业区|公寓|广场|楼|苑|中心|工业园|商业区|开发区|单位|社区))"),
        Pattern.compile("^(.*?(?:栋|号楼|座|幢))"),
        Pattern.compile("^(.*?(?:单元|梯|座|门))"),
        Pattern.compile("^(.*?(?:\\d+层|楼))"),
        Pattern.compile("^(\\d+)$")
    );

    public static Map<String, String> parseAddress(String address) {
        Map<String, String> result = new LinkedHashMap<>();
        String remaining = preprocess(address);

        for (int i = 0; i < LEVELS.length; i++) {
            Matcher matcher = PATTERNS.get(i).matcher(remaining);
            if (matcher.find()) {
                String value = matcher.group(1).trim();
                result.put(LEVELS[i], value);
                remaining = remaining.substring(matcher.end()).trim();
            } else {
                result.put(LEVELS[i], "");
            }
        }

        // 处理层和房号的特殊情况
        handleSpecialCases(result, remaining);
        return result;
    }

    private static String preprocess(String address) {
        return address.replaceAll("[\\$\\【].*?[\\$\\】]", "")
                      .replaceAll("\\$.*?\\$", "")
                      .replaceAll("【.*?】", "")
                      .trim();
    }

    private static void handleSpecialCases(Map<String, String> result, String remaining) {
        // 如果房号未提取但剩余内容有数字
        if (result.get("房号").isEmpty() && !remaining.isEmpty()) {
            Matcher matcher = Pattern.compile("(\\d+)$").matcher(remaining);
            if (matcher.find()) {
                result.put("房号", matcher.group(1));
            }
        }
    }

    public static void main(String[] args) {
        List<String> testAddresses = Arrays.asList(
            "广州市白云区同和街道白山东路同和村白山片区白山西街105号1层103",
            "广州市白云区江高镇广花四路双岗村[IPTV可选]安二街18号2层201[IPTV]",
            "广州市白云区均禾街道广花一路石马村[初装399][非千兆][IPTV可选]桃源南中街四巷2号1层104[IPTV]",
            "广州市白云区同德街道西槎路[空]得雅阁德雅街2T1层9层902[IPTV]",
            "广州市增城区新塘镇汇太东路汇美区[初装199][IPTV可选]岭南路8号4层406[IPTV]"
        );

        for (String addr : testAddresses) {
            System.out.println("解析地址: " + addr);
            Map<String, String> parsed = parseAddress(addr);
            parsed.forEach((k, v) -> System.out.println(k + ": " + v));
            System.out.println("--------------------------");
        }
    }
}